<?php

namespace App\Http\Middleware;

use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class AppVersionControl
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse|mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $versionCode = $request->header('APPCODE') ?? '';

        if (empty($versionCode) || $versionCode < Setting::get('app_code')) {
            $invites = Setting::get('invites');
            $downloadLink = !empty($invites['download_app_url']) ? $invites['download_app_url'] : $invites['local_download_url'];
            return response()->json([
                'code' => 420,
                // 'message' => '当前App版本太低，请更新到最新版本！',
                'message' => sprintf("%s|#|%s", Setting::get('app_version'), $downloadLink),
            ]);
        }

        return $next($request);
    }
}
